package org.atlantis.net.base.echotcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

/*
 * 典型的TCP客户端创建一般分为3个大致步骤： 
 * 1.创建一个Socket实例来与服务器端建立连接。
 * 2.通过Socket的输入输出流进行通信，一个Socket实例包括一个InputStream和一个OutputStream。
 * 3.使用Socket的close方法关闭连接。
 */
public class TCPEchoClient {

	private static final String SERVER_HOST = "127.0.0.1";
	private static final int SERVER_PORT = 10006;

	public static void main(String[] args) throws UnknownHostException,
			IOException {
		if (args.length != 1) {
			throw new IllegalArgumentException("Parameter(s): <message>");
		}
		// 使用默认编码将字符串格式的消息转换为字节码
		byte[] msgData = args[0].getBytes();
		Socket socket = new Socket(SERVER_HOST, SERVER_PORT);
		System.out.println("Connected to server...sending echo string.");

		InputStream in = socket.getInputStream();
		OutputStream out = socket.getOutputStream();

		out.write(msgData); // 将消息发到服务器

		// 从服务器接收到回执的信息
		int totalBytesReceived = 0; // 现在接受到的所有字节数
		int bytesReceived; // 最后一次接受的字节数
		while (totalBytesReceived < msgData.length) {
			// read方法会造成阻塞，直到读取到数据为止
			bytesReceived = in.read(msgData, totalBytesReceived, msgData.length
					- totalBytesReceived);
			if (bytesReceived == -1) {
				break;
			}
			totalBytesReceived += bytesReceived;
		}
		System.out.println("Received: " + new String(msgData));
		socket.close(); // 关闭客户端
	}
}
